<?php

namespace Wechat\Controller;

class UserCenterController extends CommonController {

    /**
     * 病例资料
     */
    public function myInfo() {

        $categoryId = $_REQUEST["categoryId"];

        if(!isNullOrEmpty($categoryId)) {
            $this->customer["category_id"] = $categoryId;
        }

        if($this->customer["valid"] != 1) {
            $this->customer["nickname"] = "";
        }

        $ownCategory = D("Category")->queryById($this->customer["category_id"]);

        $this->assign("ownCategory", $ownCategory);
        $this->assign("info", $this->customer);
        $this->display("updateInfo");
    }

    /**
     * 保存病例资料
     */
    public function updateInfo() {

        $this->customer["nickname"] = I("post.nickname");
        $this->customer["sex"] = I("post.sex");
        $this->customer["birthday"] = I("post.birthday");
        $this->customer["mobile"] = I("post.mobile");
        $this->customer["category_id"] = I("post.categoryId");
        $this->customer["doctor_name"] = I("post.doctorName");
        $this->customer["hospital_name"] = I("post.hospitalName");
        $this->customer["diagnosis"] = I("post.diagnosis");
        $this->customer["city"] = I("post.city");
        if( $this->customer["valid"] != 1){
            $this->customer["point"] += 100;
        }
        $this->customer["valid"] = 1;

        D("Customer")->updateInfo($this->customer);

        $data["code"] = 200;

        echo json_encode($data);

    }

    /**
     * 个人中心
     */
    public function index() {

        if(isNullOrEmpty($this->customer["birthday"])) {
            $this->customer["birthday"] = "暂无";
        }

        if(isNullOrEmpty($this->customer["sex"])) {
            $this->customer["sex"] = "暂无";
        }

        if(isNullOrEmpty($this->customer["mobile"])) {
            $this->customer["sex"] = "暂无";
        }

        $this->assign("customer", $this->customer);
        $this->display("index");
    }

    /**
     * 我的预约
     */
    public function myBooking() {

        $map["b.customer_id"] = $this->customer["customer_id"];
        $map["b.status"] = 1;

        $list = D("Booking")->alias("b")
            ->join("left join __PRODUCT__ p on p.product_id = b.product_id")
            ->join("left join __SHOP__ s on s.shop_id = b.shop_id")
            ->field("b.*,s.address as shop_address,p.image_url as product_image,p.product_name as product_name")
            ->where($map)
            ->order("booking_id desc")
            ->select();

        $this->assign("list", $list);
        $this->display("myBooking");
    }

    /**
     * 我的活动
     */
    public function myActivity() {

        $map["aj.customer_id"] = $this->customer["customer_id"];
        $map["aj.status"] = C("ACTIVITY_JOIN_STATUS.END_PAY");

        $list = D("ActivityJoin")->alias("aj")
            ->join("left join __ACTIVITY__ a on a.activity_id = aj.activity_id")
            ->where($map)
            ->field("a.*")
            ->order("a.activity_id desc")
            ->select();

        foreach ($list as &$item) {
            $item["day"] = date("m月d日", strtotime($item["begin_time"]));
            $item["time"] = date("H:i", strtotime($item["begin_time"]))
                ."-".date("H:i", strtotime($item["end_time"]));
        }

        $this->assign("list", $list);
        $this->display("myActivity");

    }

    /**
     * 我的订单
     */
    public function myOrder() {
        $this->display("myOrder");
    }

    /**
     * 订单列表
     */
    public function myOrderList() {

        $status = I("post.status");

        if(!isNullOrEmpty($status)) {
            $map["o.status"] = $status;
        }

        $map["o.customer_id"] = $this->customer["customer_id"];

        $list = D("Order")->alias("o")
            ->join("left join __PRODUCT__ p on p.product_id = o.product_id")
            ->where($map)
            ->order("o.order_id desc")
            ->field("o.*,p.price as single_price,p.image_url,p.product_name")
            ->select();

        foreach($list as &$item) {
            $item["measure_data"] = json_decode(html_entity_decode($item["measure_data"]) ,true);
        }

        echo json_encode($list);
    }

    /**
     * 支付页
     */
    public function payInfo() {

        $id = $_REQUEST["id"];

        if(!strstr($id, '_')){//如果id不以"_"开头
            $map["o.order_id"] = $id;
            $map["o.customer_id"] = $this->customer["customer_id"];

            $order = D("Order")->alias("o")
                ->join("left join __PRODUCT__ p on p.product_id = o.product_id")
                ->where($map)
                ->field("o.*,p.price as single_price,p.image_url,p.product_name")
                ->find();

            if(isNullOrEmpty($order)) {
                $this->redirect(U("userCenter/index"));
            }

            $pay = D("Pay")->queryById($order["pay_id"]);

            if($order["status"] != C("ORDER_STATUS.WAITING_PAY")) {
                $this->redirect(U("userCenter/index"));
            }
        }else{//如果id以"_"开头
            $map["pm.payment_id"] = substr($id,1);
            $map["pm.customer_id"] = $this->customer["customer_id"];

            $payment = D("Payment")->alias("pm")
                ->where($map)
                ->field("pm.*")
                ->find();

            if(isNullOrEmpty($payment)) {
                $this->redirect(U("userCenter/index"));
            }

            $pay = D("Pay")->queryById($payment["pay_id"]);

            if($payment["status"] != C("ORDER_STATUS.WAITING_PAY")) {
                $this->redirect(U("userCenter/index"));
            }
        }


        //支付相关
        $arr = array(
            'appid' => C('appid'),
            'mch_id' => C('mch_id'),
            'nonce_str' => $this->createNoncestr(),
            //'sign' => '',	//签名
            'body' => "希卫康产品购买",
            'out_trade_no' => $pay['out_trade_no'], //订单号
            'total_fee' => $pay['money'] * 100, //金额
            'spbill_create_ip' => get_client_ip(),
            'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/handlePayOrder', //通知地址
            'trade_type' => 'JSAPI',
            'openid' => $this->customer['openid'],
        );

        $arr['sign'] = $this->getSign($arr);  //签名

        $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

        $arr2 = $this->xmlToArray($post);

        $jsApiObj["appId"] = C('appid');
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
        $jsApiObj["signType"] = "MD5";
        $jsApiObj["paySign"] = $this->getSign($jsApiObj);

        //$order["qrcode"] = "http://xwk-file.oss-cn-qingdao.aliyuncs.com/Home/IowaBraceQr".$order["number"].".jpg";

        $this->assign("pay", $pay);
        $this->assign("webarr", $jsApiObj);
        $this->assign("appId", C("appid"));
        $this->assign("config", $this->signature());

        $this->display("payInfo");

    }


    /**
     * 我的订单详情
     */
    public function orderInfo() {

        $id = $_REQUEST["id"];

        $map["o.order_id"] = $id;
        $map["o.customer_id"] = $this->customer["customer_id"];

        $order = D("Order")->alias("o")
            ->join("left join __PRODUCT__ p on p.product_id = o.product_id")
            ->where($map)
            ->field("o.*,p.price as single_price,p.image_url,p.product_name")
            ->find();

        if(isNullOrEmpty($order)) {
            $this->redirect(U("userCenter/index"));
        }

        $pay = D("Pay")->queryById($order["pay_id"]);

        if($order["status"] == C("ORDER_STATUS.WAITING_PAY")) {

            //支付相关
            $arr = array(
                'appid' => C('appid'),
                'mch_id' => C('mch_id'),
                'nonce_str' => $this->createNoncestr(),
                //'sign' => '',	//签名
                'body' => "希卫康产品购买",
                'out_trade_no' => $pay['out_trade_no'], //订单号
                'total_fee' => $pay['money'] * 100, //金额
                'spbill_create_ip' => get_client_ip(),
                'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/handlePayOrder', //通知地址
                'trade_type' => 'JSAPI',
                'openid' => $this->customer['openid'],
            );

            $arr['sign'] = $this->getSign($arr);  //签名

            $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

            $arr2 = $this->xmlToArray($post);

            $jsApiObj["appId"] = C('appid');
            $timeStamp = time();
            $jsApiObj["timeStamp"] = "$timeStamp";
            $jsApiObj["nonceStr"] = $this->createNoncestr();
            $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $this->getSign($jsApiObj);

            $this->assign("webarr", $jsApiObj);
            $this->assign("appId", C("appid"));
            $this->assign("config", $this->signature());
        }

        $this->assign("pay", $pay);
        $this->assign("info", $order);
        $this->display("orderInfo");

    }

    public function about() {

        $map["type"] = "about";

        $content = D("Content")->where($map)->find();

        $this->assign("content", $content);

        $this->display("about");

    }

    public function photo() {

        $map["type"] = "photo";

        $content = D("Content")->where($map)->find();

        $this->assign("content", $content);

        $this->display("photo");

    }

    public function team() {

        $map["type"] = "team";

        $content = D("Content")->where($map)->find();

        $this->assign("content", $content);

        $this->display("team");

    }

    /**
     * 留言
     */
    public function messagebox() {
        $customerId = $this->customer["customer_id"];

        $messageMap["customer_id"] = $customerId;
        $messageMap["day"] = date("Y-m-d");
        $messagebox = D("Messagebox")->queryByMap($messageMap);

        $ownProduct = D("Product")->queryById($messagebox["product_id"]);

        $this->assign("customerId", $customerId);
        $this->assign("ownProduct", $ownProduct);
        $this->assign("info", $messagebox);
        $this->display("messagebox");

    }

    /**
     * 提交留言
     */
    public function updateMessagebox() {

        $messagebox = D("Messagebox")->queryById(I("post.messageId"));

        $messagebox["customer_id"] = I("post.customerId");
        $messagebox["product_id"] = I("post.productId");
        $messagebox["day"] = date("Y-m-d");
        $messagebox["create_time"] = getCurrentDate();
        $messagebox["number"] = I("post.number");
        $messagebox["city"] = I("post.city");
        $messagebox["message_content"] = I("post.messageContent");
        $messagebox["status"] = C("MESSAGEBOX_STATUS.WAITING_REPLY");

        if(!isNullOrEmpty($messagebox["messagebox_id"])){
            D("Messagebox")->updateInfo($messagebox);
        }else{
            D("Messagebox")->add($messagebox);
        }

        //推送预约信息到管理员
//        $notifyData["openid"] = array("otBeowu8bYi2HBRTMBWSIWzzkkbo","otBeowlAfkwtcoHunTHTDVQucZ_E","otBeowv0VZQORekZps57qRBc5d_0");
        //$notifyData["openid"] = "otBeowu8bYi2HBRTMBWSIWzzkkbo";
        $notifyData["first"] = "收到患者留言，请通知相关销售。";
        $notifyData["keyword1"] = I("post.number");
        $notifyData["keyword2"] = $messagebox["create_time"];
        $notifyData["keyword3"] = "所在城市：【".$messagebox["city"]."】，咨询产品：【".I("post.productName")."】。";
        $notifyData["remark"] = "留言内容：【".$messagebox["message_content"]."】。";
        messageboxReceiveNotify($notifyData);

        $data["code"] = 200;

        echo json_encode($data);

    }
}